// Label Designer: extracted JS from template
(function () {
  function ready(fn) {
    if (document.readyState !== 'loading') fn();
    else document.addEventListener('DOMContentLoaded', fn);
  }

  function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        if (cookie.substring(0, name.length + 1) === name + '=') {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }

  function showAlert(type, message) {
    const div = document.createElement('div');
    div.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    div.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    div.innerHTML = `${message}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
    document.body.appendChild(div);
    setTimeout(() => div.remove(), 5000);
  }

  const sizeMapping = {
    '8mm': { width: 64, height: 200 },
    '12mm': { width: 96, height: 200 },
    '18mm': { width: 144, height: 200 },
    '24mm': { width: 192, height: 200 },
    '36mm': { width: 288, height: 200 },
  };

  // state
  let availableFields = [];
  let selectedFields = [];
  let currentFieldIndex = -1;
  let currentLabelSize = '24mm';
  let templateId = null;

  function updateSizeIndicator() {
    const el = document.getElementById('sizeIndicator');
    if (el) el.textContent = currentLabelSize;
  }

  function updateLabelCanvas() {
    const canvas = document.getElementById('labelCanvas');
    if (!canvas) return;
    const sizeInfo = sizeMapping[currentLabelSize];
    if (sizeInfo) {
      canvas.style.width = `${sizeInfo.height * 2}px`;
      canvas.style.height = `${sizeInfo.width * 2}px`;
      updateSizeIndicator();
    }
  }

  function loadAvailableFields() {
    const container = document.getElementById('availableFields');
    if (!container) return;
    container.innerHTML = '';
    availableFields.forEach((field) => {
      const fieldItem = document.createElement('div');
      fieldItem.className = 'field-item';
      fieldItem.innerHTML = `
        <div class="field-info">
          <div class="field-name">${field.label}</div>
          <div class="field-type">${field.type}</div>
        </div>
        <div class="field-actions">
          <button class="btn btn-sm btn-primary" data-add-field="${field.name}">
            <i class="fas fa-plus"></i>
          </button>
        </div>`;
      container.appendChild(fieldItem);
    });
  }

  function updateSelectedFieldsList() {
    const container = document.getElementById('selectedFields');
    if (!container) return;

    if (selectedFields.length === 0) {
      container.innerHTML = `
        <div class="text-center text-muted py-3">
          <i class="fas fa-mouse-pointer"></i>
          <p class="mb-0">点击左侧字段添加到标签</p>
        </div>`;
      return;
    }

    container.innerHTML = '';
    selectedFields.forEach((field, index) => {
      const fieldItem = document.createElement('div');
      fieldItem.className = 'selected-field-item';
      fieldItem.innerHTML = `
        <div class="field-info">
          <strong>${field.label}</strong>
          <small class="text-muted d-block">${field.type} | ${field.font_size}</small>
        </div>
        <div class="field-controls">
          <button class="btn-field-action btn-move-up" data-move-up="${index}" ${index === 0 ? 'disabled' : ''}>
            <i class="fas fa-arrow-up"></i>
          </button>
          <button class="btn-field-action btn-move-down" data-move-down="${index}" ${index === selectedFields.length - 1 ? 'disabled' : ''}>
            <i class="fas fa-arrow-down"></i>
          </button>
          <button class="btn-field-action btn-config" data-config="${index}">
            <i class="fas fa-cog"></i>
          </button>
          <button class="btn-field-action btn-remove" data-remove="${index}">
            <i class="fas fa-times"></i>
          </button>
        </div>`;
      container.appendChild(fieldItem);
    });
  }

  function refreshPreview() {
    const canvas = document.getElementById('labelCanvas');
    if (!canvas) return;
    if (selectedFields.length === 0) {
      canvas.innerHTML = `
        <div class="size-indicator" id="sizeIndicator">${currentLabelSize}</div>
        <div class="text-center text-muted py-5">
          <i class="fas fa-tags fa-3x mb-3"></i>
          <p>标签预览将在这里显示</p>
          <small>选择字段并配置后可看到预览效果</small>
        </div>`;
      return;
    }

    const customText = document.getElementById('customText')?.value || '';
    const previewData = {
      label_size: currentLabelSize,
      fields_config: selectedFields,
      template_design: {},
      custom_data: { custom_text: customText },
      asset_id: null,
    };

    canvas.innerHTML = `
      <div class="size-indicator" id="sizeIndicator">${currentLabelSize}</div>
      <div class="text-center py-4">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">生成预览...</span>
        </div>
        <p class="mt-2 text-muted">正在生成预览...</p>
      </div>`;

    fetch('/label-preview/', {
      method: 'POST',
      headers: {
        'X-CSRFToken': getCookie('csrftoken'),
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(previewData),
    })
      .then((r) => r.json())
      .then((data) => {
        if (data.success) {
          canvas.innerHTML = `
            <div class="size-indicator" id="sizeIndicator">${currentLabelSize}</div>
            <img src="${data.image_data}" alt="标签预览" style="max-width: 100%; max-height: 100%;" loading="lazy" decoding="async">
          `;
        } else {
          canvas.innerHTML = `
            <div class="size-indicator" id="sizeIndicator">${currentLabelSize}</div>
            <div class="alert alert-danger">
              <i class="fas fa-exclamation-triangle"></i>
              ${data.message || '预览生成失败'}
            </div>`;
        }
      })
      .catch(() => {
        canvas.innerHTML = `
          <div class="size-indicator" id="sizeIndicator">${currentLabelSize}</div>
          <div class="alert alert-danger">
            <i class="fas fa-exclamation-triangle"></i>
            预览生成失败
          </div>`;
      });
  }

  function addField(fieldName) {
    const field = availableFields.find((f) => f.name === fieldName);
    if (!field) return;
    if (selectedFields.find((f) => f.name === fieldName)) {
      showAlert('warning', '字段已存在');
      return;
    }
    const fieldConfig = {
      name: field.name,
      label: field.label,
      type: field.type,
      show_label: true,
      font_size: 'medium',
    };
    if (field.type === 'qrcode') fieldConfig.qr_size = 'medium';
    if (field.type === 'barcode') fieldConfig.barcode_height = 'medium';
    selectedFields.push(fieldConfig);
    updateSelectedFieldsList();
    refreshPreview();
    showAlert('success', `已添加字段: ${field.label}`);
  }

  function configureField(index) {
    const field = selectedFields[index];
    if (!field) return;
    const label = document.getElementById('fieldLabel');
    const showLabel = document.getElementById('showLabel');
    const fontSize = document.getElementById('fontSize');
    const qrCfg = document.getElementById('qrCodeConfig');
    const barCfg = document.getElementById('barcodeConfig');
    if (!label || !showLabel || !fontSize) return;
    label.value = field.label;
    showLabel.checked = field.show_label;
    fontSize.value = field.font_size;
    if (qrCfg) qrCfg.style.display = field.type === 'qrcode' ? 'block' : 'none';
    if (barCfg) barCfg.style.display = field.type === 'barcode' ? 'block' : 'none';
    if (field.type === 'qrcode') document.getElementById('qrCodeSize').value = field.qr_size || 'medium';
    if (field.type === 'barcode') document.getElementById('barcodeHeight').value = field.barcode_height || 'medium';
    currentFieldIndex = index;
    if (window.bootstrap) new window.bootstrap.Modal(document.getElementById('fieldConfigModal')).show();
  }

  function saveFieldConfig() {
    if (currentFieldIndex < 0) return;
    const field = selectedFields[currentFieldIndex];
    field.show_label = document.getElementById('showLabel').checked;
    field.font_size = document.getElementById('fontSize').value;
    if (field.type === 'qrcode') field.qr_size = document.getElementById('qrCodeSize').value;
    if (field.type === 'barcode') field.barcode_height = document.getElementById('barcodeHeight').value;
    updateSelectedFieldsList();
    refreshPreview();
    if (window.bootstrap) window.bootstrap.Modal.getInstance(document.getElementById('fieldConfigModal')).hide();
    showAlert('success', '字段配置已保存');
  }

  function removeField(index) {
    selectedFields.splice(index, 1);
    updateSelectedFieldsList();
    refreshPreview();
    showAlert('info', '字段已移除');
  }

  function saveTemplate() {
    const templateData = {
      name: document.getElementById('templateName').value,
      description: document.getElementById('templateDescription').value,
      label_size: currentLabelSize,
      printer_model: document.getElementById('printerModel').value,
      fields_config: selectedFields,
      template_design: {},
      print_settings: {},
      is_public: document.getElementById('isPublic').checked,
    };
    if (templateId) templateData.template_id = templateId;

    const errors = [];
    if (!templateData.name) errors.push('请输入模板名称');
    if (selectedFields.length === 0) errors.push('请至少选择一个字段');
    if (errors.length > 0) {
      const box = document.getElementById('saveValidationErrors');
      if (box) {
        box.innerHTML = errors.join('<br>');
        box.style.display = 'block';
      }
      if (window.bootstrap) new window.bootstrap.Modal(document.getElementById('saveModal')).show();
      return;
    }

    const url = '/label-templates/save/';
    fetch(url, {
      method: 'POST',
      headers: {
        'X-CSRFToken': getCookie('csrftoken'),
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(templateData),
    })
      .then((r) => {
        if (r.status === 409) {
          return r.json().then((data) => {
            // inline validation on name field
            const nameInput = document.getElementById('templateName');
            if (nameInput) {
              nameInput.classList.add('is-invalid');
              let feedback = nameInput.nextElementSibling;
              if (!feedback || !feedback.classList || !feedback.classList.contains('invalid-feedback')) {
                feedback = document.createElement('div');
                feedback.className = 'invalid-feedback';
                nameInput.parentNode && nameInput.parentNode.insertBefore(feedback, nameInput.nextSibling);
              }
              feedback.textContent = data.message || '已存在同名的标签模板，请更换名称';
            }
            // keep modal open and show toast
            showAlert('warning', data.message || '名称已存在');
            throw new Error('name_conflict');
          });
        }
        return r.json();
      })
      .then((data) => {
        if (data && data.success) {
          showAlert('success', data.message || '保存成功');
          if (window.bootstrap) window.bootstrap.Modal.getInstance(document.getElementById('saveModal'))?.hide();
          setTimeout(() => (window.location.href = '/label-templates/'), 1000);
        } else if (data) {
          showAlert('danger', data.message || '保存失败');
        }
      })
      .catch(() => showAlert('danger', '保存失败'));
  }

  function initFromBoot() {
    let boot = {};
    const el = document.getElementById('label-designer-boot');
    if (el) {
      try {
        boot = JSON.parse(el.textContent || '{}');
      } catch (e) {
        boot = {};
      }
    } else if (window.LabelDesignerBoot) {
      boot = window.LabelDesignerBoot;
    }
    availableFields = boot.availableFields || [];
    currentLabelSize = boot.currentLabelSize || '24mm';
    templateId = (boot.template && boot.template.id) || null;
    if (boot.template && Array.isArray(boot.template.fields_config)) {
      selectedFields = boot.template.fields_config || [];
    }
  }

  function bindToolbar() {
    const toolbar = document.querySelector('.designer-toolbar');
    if (!toolbar) return;
    toolbar.addEventListener('click', function (e) {
      const btn = e.target.closest('button');
      if (!btn) return;
      if (btn.getAttribute('onclick')?.includes('previewLabel')) {
        e.preventDefault();
        refreshPreview();
      }
      if (btn.getAttribute('onclick')?.includes('saveTemplate')) {
        e.preventDefault();
        const modal = document.getElementById('saveModal');
        if (modal && window.bootstrap) new window.bootstrap.Modal(modal).show();
      }
    });
  }

  function bindSidebar() {
    // size options
    document.querySelectorAll('.size-option').forEach((opt) => {
      opt.addEventListener('click', function () {
        document.querySelectorAll('.size-option').forEach((o) => o.classList.remove('selected'));
        this.classList.add('selected');
        currentLabelSize = this.dataset.size;
        updateSizeIndicator();
        updateLabelCanvas();
      });
    });

    // add field buttons
    const available = document.getElementById('availableFields');
    if (available) {
      available.addEventListener('click', function (e) {
        const addBtn = e.target.closest('[data-add-field]');
        if (addBtn) addField(addBtn.getAttribute('data-add-field'));
      });
    }

    // selected fields controls
    const selected = document.getElementById('selectedFields');
    if (selected) {
      selected.addEventListener('click', function (e) {
        const up = e.target.closest('[data-move-up]');
        const down = e.target.closest('[data-move-down]');
        const cfg = e.target.closest('[data-config]');
        const rm = e.target.closest('[data-remove]');
        if (up) {
          const i = parseInt(up.getAttribute('data-move-up'), 10);
          if (i > 0) {
            [selectedFields[i], selectedFields[i - 1]] = [selectedFields[i - 1], selectedFields[i]];
            updateSelectedFieldsList();
            refreshPreview();
          }
        }
        if (down) {
          const i = parseInt(down.getAttribute('data-move-down'), 10);
          if (i < selectedFields.length - 1) {
            [selectedFields[i], selectedFields[i + 1]] = [selectedFields[i + 1], selectedFields[i]];
            updateSelectedFieldsList();
            refreshPreview();
          }
        }
        if (cfg) {
          const i = parseInt(cfg.getAttribute('data-config'), 10);
          currentFieldIndex = i;
          configureField(i);
        }
        if (rm) {
          const i = parseInt(rm.getAttribute('data-remove'), 10);
          removeField(i);
        }
      });
    }

    // custom text immediate refresh
    const customText = document.getElementById('customText');
    if (customText) customText.addEventListener('change', refreshPreview);

    // save modal confirm
    const confirmBtn = document.querySelector('#saveModal .btn.btn-primary');
    if (confirmBtn) confirmBtn.addEventListener('click', saveTemplate);
  }

  ready(function () {
    initFromBoot();
    loadAvailableFields();
    updateSelectedFieldsList();
    bindToolbar();
    bindSidebar();
    updateLabelCanvas();
    if (selectedFields.length) refreshPreview();

    // clear name validation on input
    const nameInput = document.getElementById('templateName');
    if (nameInput) {
      nameInput.addEventListener('input', function () {
        this.classList.remove('is-invalid');
        const sib = this.nextElementSibling;
        if (sib && sib.classList && sib.classList.contains('invalid-feedback')) {
          sib.textContent = '';
        }
      });
    }

    // expose API for legacy onclick attributes
    window.LabelDesigner = {
      refreshPreview,
      saveFieldConfig,
      saveTemplate,
    };

    // shims for existing inline handlers in template
    window.refreshPreview = refreshPreview;
    window.previewLabel = refreshPreview;
    // toolbar save button should open modal; confirmSave will actually persist
    window.saveTemplate = function () {
      const modal = document.getElementById('saveModal');
      if (modal && window.bootstrap) new window.bootstrap.Modal(modal).show();
    };
    window.confirmSave = function () {
      saveTemplate();
    };
  });
})();
